/**
 * 
 */
package cre.gutwo.imp;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.FilenameUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import cre.gutwo.domain.DataModel;

/**
 * @author Cre.Gu
 *
 */
public abstract class DefaultImp implements Imper{

	@Override
	public List<DataModel> gainOrgiDatas(String file, String type, Map<String, String> context) {
		List<DataModel> results = new ArrayList<DataModel>();
		try {
			return doPoi(file);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return results;
	}

	@SuppressWarnings("resource")
	protected List<DataModel> doPoi(String file) throws Exception {
		List<DataModel> results = new ArrayList<DataModel>();
		File f = new File(file);

		InputStream is = new FileInputStream(f);

		String ext = FilenameUtils.getExtension(f.getName());
		Workbook wb = null;

		if ("xls".equals(ext)) {
			wb = new HSSFWorkbook(is);
		} else if ("xlsx".equals(ext)) {
			wb = new XSSFWorkbook(is);
		} else {
			throw new Exception("无效的后缀名");
		}
		Sheet sheet = wb.getSheetAt(0);

		for (Row row : sheet) {
			if (row.getRowNum() < 2)
				continue;

			DataModel dm = new DataModel();

			for (Cell cell : row) {
				// 前提，所有表格格式一致，标题列顺序不变
				putValue(dm, cell);
			}

			results.add(dm);
		}
		return results;
	}

	protected abstract void putValue(DataModel dm, Cell cell);
}
